<?php
namespace ac\modules\member\controllers;

use Yii;
use ac\controllers\BasicController;
use yii\web\Controller;
use app\models\Opened;
use app\modules\member\models\Member;
use app\modules\member\models\MemberCoupon;
use app\models\CouponTpl;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;

class CouponController extends BasicController
{
    protected $memberInfo;//登录信息

    public function init()
    {
        parent::init();
        if(isset($this->session->get('memberInfo')->loginname)){
            $this->memberInfo = $this->session->get('memberInfo');
        };
    }

    /*券模板列表 后台、前台都可以使用*/
    public function actionCouponTpl()
    {
        $comid = isset($this->get['comid'])?$this->get['comid']:'';
        if(!empty($comid)){
            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }
            if(isset($this->get['pagesize'])){
                $pageSize = intval($this->get['pagesize']?$this->get['pagesize']:Tool::getPageSize());
            }else{
                $pageSize = Tool::getPageSize();
            }

            $couponTpl = new CouponTpl;
            $count = $couponTpl::find()
                                ->where('comid = :comid', [':comid' => $comid])
                                ->count();
            $couponTpl = $couponTpl::find()
                              ->select(['cid', 'couponname', 'flag', 'condition_amount', 'amount', 'discount', 'remark', 'circulation', 'receive_num', 'begin_time', 'end_time'])
                              ->where('comid = :comid and circulation > receive_num', [':comid' => $comid])
                              ->offset($pageSize*($currPage-1))->limit($pageSize)
                              ->orderBy(['cid' => SORT_DESC])
                              ->asArray()->all();
        }else{
            $currPage = 1;
            $count = 0;
            $pageSize = 0;
            $couponTpl = [];
        }
        $res = array(
            'list' => $couponTpl,
            'pageInfo' => array(
                'count' => intval($count),
                'currPage' => $currPage,
                'pageSize' => $pageSize,
            ),
        );
        // P($res);
        return Tool::showRes([0, '获取成功'], $res);
    }

    /*发放优惠券 仅子应用使用*/
    public function actionSendCoupon()
    {
        if(Yii::$app->request->isPost 
            and isset($this->post['comid']) 
            and isset($this->post['appid']) 
            and isset($this->post['member_id']) 
            and isset($this->post['id'])//券模板ID
            and isset($this->post['secretkey'])
            and $this->post['secretkey'] == $this->params['secretkey']['ac']){

            /*验证appid是否存在*/
            $opened = Opened::find()->select('appid')
                            ->where('comid = :comid and appid = :appid', [':comid' => $this->post['comid'], ':appid' => $this->post['appid']])
                            ->one();
            // P($opened);

            $member = Member::find()->select(['member_id'])
                            ->where('member_id = :id and comid = :comid', [':id' => $this->post['member_id'], ':comid' => $this->post['comid']])
                            ->one();
            // P($member);
            if(!is_null($opened) or !is_null($member)){
                /*验证券模板是否存在，如存在，判断库存*/
                $couponTpl = CouponTpl::find()
                                ->select(['cid', 'couponname', 'flag', 'condition_amount', 'amount', 'discount', 'remark', 'begin_time', 'end_time', 'circulation', 'receive_num'])
                                ->where('cid = :id', [':id' => $this->post['id']])
                                ->one();
                // P($couponTpl);
                if(!is_null($couponTpl)){
                    if(($couponTpl->circulation - $couponTpl->receive_num) <= 0){//有库存
                        $backInfo = ErrMap::getError(10028);//返回信息 优惠券已发送完
                    }else{
                        $transaction = Yii::$app->db->beginTransaction();//事物处理
                        $pass = true;
                        try{
                            /*1、增加会员优惠券数量*/
                            if($pass){
                                if( !Member::updateAllCounters(['curr_coupons' => 1], 'member_id = :memberid', [':memberid' => $member->member_id]) ){
                                    $pass = false;
                                    $backInfo = ErrMap::getError(10029);//返回信息
                                }
                            };

                            /*2、增加我的优惠券记录*/
                            if($pass){
                                $memberCoupon = new MemberCoupon;
                                $data = array(
                                    'MemberCoupon' => array(
                                        'getbyappid' => $opened->appid,
                                        'member_id' => $member->member_id,
                                        'cid' => $couponTpl->cid,
                                        'couponname' => $couponTpl->couponname,
                                        'flag' => $couponTpl->flag,
                                        'condition_amount' => $couponTpl->condition_amount,
                                        'amount' => $couponTpl->amount,
                                        'discount' => $couponTpl->discount,
                                        'remark' => $couponTpl->remark,
                                        'begin_time' => $couponTpl->begin_time,
                                        'end_time' => $couponTpl->end_time,
                                        'remark' => $couponTpl->remark,
                                    )
                                );
                                // P($data);
                                if(!$memberCoupon->addCoupon($data)){
                                    $pass = false;
                                    if($memberCoupon->hasErrors()){
                                        $backInfo = ErrMap::getError(10005);//返回信息
                                        $exception = $memberCoupon->getErrors();//异常信息
                                    }
                                }
                            }

                            /*3、减少库存*/
                            if($pass){
                                $couponTpl->receive_num = $couponTpl->receive_num + 1;
                                if( !$couponTpl->save() ){
                                    $pass = false;
                                    $backInfo = ErrMap::getError(10029);//返回信息
                                }
                            }

                            if($pass){
                                $backInfo = [0, '添加优惠券成功'];//返回信息
                                $transaction->commit();
                            }
                        }catch(\Exception $exception){
                            $transaction->rollback();       
                        };
                    }
                }
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
        return Tool::showRes(ErrMap::getError(10005));
    }


    /*核销我的优惠券*/
    public function actionUseCoupon()
    {
        if(Yii::$app->request->isPost 
            and isset($this->post['appid']) 
            and isset($this->post['member_id']) 
            and isset($this->post['code'])//券码
            and isset($this->post['secretkey'])
            and $this->post['secretkey'] == $this->params['secretkey']['ac']){
            // P($this->post);
            /*取出券信息*/
            $memberCoupon = MemberCoupon::find()
                                ->where('coupon_code = :code and member_id = :mid and isuse = 1', [':code' => $this->post['code'], ':mid' => $this->post['member_id']])
                                ->one();
            // P($memberCoupon);

            /*验证appid是否存在*/
            $opened = Opened::find()->select('appid')
                            ->where('appid = :appid', [':appid' => $this->post['appid']])
                            ->one();
            // P($opened);

            if(!is_null($memberCoupon) and !is_null($opened)){
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    /*1、减少会员优惠券数量*/
                    if($pass){
                        if( !Member::updateAllCounters(['curr_coupons' => -1], 'member_id = :memberid', [':memberid' => $memberCoupon->member_id]) ){
                            $pass = false;
                            $backInfo = ErrMap::getError(10029);//返回信息
                        }
                    };

                    /*2、核销优惠前*/
                    if($pass){
                        $memberCoupon->usebyappid = $opened->appid;
                        $memberCoupon->isuse = 2;
                        $memberCoupon->use_time = date('Y-m-d h:i:s', time());
                        $memberCoupon->useremark = isset($this->post['useremark'])?$this->post['useremark']:'';
                        if(!$memberCoupon->save()){
                            $pass = false;
                            $backInfo = ErrMap::getError(10030);//返回信息
                        }
                    }

                    if($pass){
                        $backInfo = [0, '核销我的优惠券成功'];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };
            }
        }

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*反核销我的优惠券*/
    public function actionCancelCoupon()
    {
        if(Yii::$app->request->isPost 
            and isset($this->post['appid']) 
            and isset($this->post['member_id']) 
            and isset($this->post['code'])//券码
            and isset($this->post['secretkey'])
            and $this->post['secretkey'] == $this->params['secretkey']['ac']){
            // P($this->post);
            /*取出券信息*/
            $memberCoupon = MemberCoupon::find()
                                ->where('coupon_code = :code and member_id = :mid and isuse = 2', [':code' => $this->post['code'], ':mid' => $this->post['member_id']])
                                ->one();
            // P($memberCoupon);

            /*验证appid是否存在*/
            $opened = Opened::find()->select('appid')
                            ->where('appid = :appid', [':appid' => $this->post['appid']])
                            ->one();
            // P($opened);

            if(!is_null($memberCoupon) and !is_null($opened)){
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    /*1、增加会员优惠券数量*/
                    if($pass){
                        if( !Member::updateAllCounters(['curr_coupons' => 1], 'member_id = :memberid', [':memberid' => $memberCoupon->member_id]) ){
                            $pass = false;
                            $backInfo = ErrMap::getError(10029);//返回信息
                        }
                    };

                    /*2、核销优惠前*/
                    if($pass){
                        $memberCoupon->isuse = 1;
                        $memberCoupon->cancel_time = date('Y-m-d h:i:s', time());
                        $memberCoupon->cancelremark = isset($this->post['cancelremark'])?$this->post['cancelremark']:'';
                        if(!$memberCoupon->save()){
                            $backInfo = ErrMap::getError(10030);//返回信息
                        }
                    }

                    if($pass){
                        $backInfo = [0, '反核销我的优惠券成功'];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };

                
            }
        }

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*删除我的优惠券 仅前台使用*/
    public function actionDelCoupon()
    {
        // $this->memberInfo = (object)array(
        //     'member_id' => 24
        // );
        /*如果没有登录，自动登录*/
        if(!isset($this->memberInfo)){
            Yii::$app->runAction('member/login/getinfo-by-openid');
        }


        if(isset($this->memberInfo)){
            $id = isset($this->post['id'])?$this->post['id']:'';
            if($id){
                if( MemberCoupon::updateAll(['isdel' => 2], 'id = :id', [':id' => $id]) ){//删除成功
                    $backInfo = [0, '删除我的优惠券成功'];//返回信息
                }else{//删除失败
                    $backInfo = ErrMap::getError(10013, '删除我的优惠券失败');//返回信息
                }
                //操作日志
                if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, '', $this->memberInfo), '') ) != 'boolean'){
                    return $res;
                };
            }
            return Tool::showRes(ErrMap::getError(10005));
        }else{
            list($errno, $errmsg) = ErrMap::getError(10007);
            return Tool::showRes([$errno, $errmsg]);
        }
    }

    /*获取我的优惠券 仅供前台使用*/
    public function actionCouponList()
    {
        // $this->memberInfo = (object)array(
        //     'member_id' => 24
        // );
        if(isset($this->memberInfo)){
            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }

            if(isset($this->get['pagesize'])){
                $pageSize = intval($this->get['pagesize']?$this->get['pagesize']:Tool::getPageSize());
            }else{
                $pageSize = Tool::getPageSize();
            }

            $where = '';
            if(isset($this->get['isuse'])){
                $isuse = intval($this->get['isuse']?$this->get['isuse']:'');
                if(!empty($isuse)){
                    if($isuse == 1){
                        $where = ' and isuse = 1';
                    }else if($isuse == 2){
                        $where = ' and isuse = 2';
                    }else if($isuse == 3){
                        $where = ' and isuse = 1 and end_time < "' . date('y-m-d h:i:s', time()) . '"';
                    }
                }
            }

            $memberCoupon = new MemberCoupon;
            $count = $memberCoupon::find()
                            ->where('isdel = 1 and member_id = :mid' . $where, [':mid' => $this->memberInfo->member_id])
                            ->count();
            $memberCouponList = $memberCoupon::find()
                            ->select(['coupon_code', 'couponname', 'flag', 'condition_amount', 'amount', 'discount', 'remark', 'begin_time', 'end_time', 'isuse'])
                            ->where('isdel = 1 and member_id = :mid' . $where, [':mid' => $this->memberInfo->member_id])
                            ->orderBy(['id' => SORT_DESC])
                            ->offset($pageSize*($currPage-1))->limit($pageSize)
                            ->asArray()->all();
            $res = array(
                'list' => $memberCouponList,
                'pageInfo' => array(
                    'count' => intval($count),
                    'currPage' => $currPage,
                    'pageSize' => $pageSize,
                ),
            );
            // p($res);
            return Tool::showRes([0, '获取成功'], $res);
        }else{
            list($errno, $errmsg) = ErrMap::getError(10007);
            return Tool::showRes([$errno, $errmsg]);
        }
    }


}
